﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace Server
{
    static class ServerCore
    {
        private static TcpListener listener;
        private static byte[] buffer = new byte[1024];
        private static int count;
        private static bool isLisitening = false;

        private static void listening()
        {
            while (isLisitening)
            {
                TcpClient client = listener.AcceptTcpClient();
                NetworkStream stream = client.GetStream();
                count = stream.Read(buffer, 0, buffer.Length);
                ReceivingMessageEvent();
                stream.Close();
                client.Close();
            }
        }

        public delegate void ReceivingMessageHandler();
        public static event ReceivingMessageHandler ReceivingMessageEvent;

        public static void Start()
        {
            listener = new TcpListener(Dns.GetHostAddresses("localhost")[0], 13);
            listener.Start();
            count = 0;
            isLisitening = true;

            Thread listenThread = new Thread(new ThreadStart(listening));
            listenThread.Start();
        }

        public static void Stop()
        {
            isLisitening = false;
            listener.Stop();
        }

        public static int Count
        {
            get { return count; }
        }

        public static string Receive()
        {
            string received;
            lock (buffer)
            {
                received = Encoding.ASCII.GetString(buffer, 0, count);
                count = 0;
            }
            return received;
        }
    }
}
